<?php
namespace control;
/*
* 公文模板类
*/

class officialDocumentModelClass extends adIndexClass
{
    private const page = 'officialDocumentModel';
    private const table = 'official_document_template';
    private const title = '公文模板';
    public array $stateOption = ['启用', '停用'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'      => [
                        'name'  => "公文种类",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "模板名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'stid'  => [
                        'name'  => "创建人",
                        'width' => 300,
                    ],
                    'state'         => [
                        'name'  => '状态',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'updateTime'          => [
                        'name'  => '更新时间',
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "公文种类" => select(array("name" => "type", "option" => explode('，',para('officialDocumentType')))),
                    "模板名称"     => text(array("name" => "name")),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            "type" => $this->post('type'),
            "state" => $this->post('state')
        );

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=preview&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function stateSwitch()
    {
        $type = $this->post('type');
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html , 'formTwo' => $formName));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit()
    {
        $type = $this->post('type');
        $idArr = $this->post('id')?[$this->post('id')]:$this->post('listId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($type, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $json['warn'] = update(array('table' => self::table, 'field' => ['state' => $type], 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$type}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }

        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     *
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "公文种类：" => select(array('name' => 'type', 'title' => '公文种类', 'option' => explode('，', para('officialDocumentType')), 'value' => $info['type'])),
                    must . "模板名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                ],
                [
                    must . "标题：" => text(["name" => "title", 'class' => 'text', "value" => $info['title']]),
                    must . "发文单位：" => text(["name" => "issueUnit", 'class' => 'long', "value" => $info['issueUnit']]),
                ],
                [
                    "发文字：" => select(array('name' => 'prefix', 'title' => '请选择', 'option' => explode('，', para('officialDocumentPrefix')), 'value' => $info['prefix'])),
                    must ."主送：" => text(["name" => "department", 'class' => 'long', "value" => $info['department']])
                ],
                [
                    "主题词：" => componentClass::singleInput(array('list'=>explode(',',$info['tag']))),
                ],
                [
                    "抄送：" => text(["name" => "copyDept", 'class' => 'long', "value" => $info['copyDept']]),
                    "印发：" =>  text(["name" => "issuedDept", 'class' => 'long', "value" => $info['issuedDept']])
                ],
                [
                    must ."正文：" => textarea(["name" => "content", 'class' => 'textarea', "value" => $info['content']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 400, "html" => $html));
    }

    public function editEdit()
    {
        $label_name = $this->post('label_name')?:[];
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'name' => $this->post('name'),
            'title' => $this->post('title'),
            'issueUnit' => $this->post('issueUnit'),
            'prefix' => $this->post('prefix'),
            'department' => $this->post('department'),
            'copyDept' => $this->post('copyDept'),
            'issuedDept' => $this->post('issuedDept'),
            'content' => $this->post('content'),
            'tag'=>implode(',',$label_name)
        ];
        $annotation = [
            'type' => '公文种类',
            'name' => '模板名称',
            'title' => '标题',
            'issueUnit' => '发文单位',
            'department' => '主送',
            'content' => '正文',
        ];
        $rules = [
            'type' => 'required',
            'name' => 'required',
            'title' => 'required',
            'issueUnit' => 'required',
            'department' => 'required',
            'content' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,"where"=>"name = '$field[name]' and id !='$id'")) >0){
            $json['warn'] = '已存在此合同模板名称';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'state' => '启用',
                    'time' => $this->time,
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $state = $info['state'] == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $state,
                    "type" => "点击事件",
                    'title' => '修改状态',
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$state}'})",
                ];

            }
            if ($this->power(self::page, "del")) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //按钮
            $button[] = [
                "name" => "预览",
                "type" => "点击事件",
                "title" => "预览",
                'fun' => "window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=preview&method=preview&id={$info['id']}')"
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "公文种类" => $info['type'],
                        "模板名称" => $info['name'],
                        "状态" => $info['state'],
                        "创建人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function preview(): string
    {
        $table = $this->get('table')?:self::table;
        $info = query($table,"id = '".$this->get('id')."'");
        $file = '';
        $all = find(array('table'=>'file',"where"=>"targetId = '$info[id]' order by time asc"));
        foreach ($all['array'] as $array){
            $array['src'] = root.$array['src'];
            $file .= "<a download='{$array['name']}' href='{$array['src']}'>附件：{$array['name']}</a><br>";
        }

        $info['preText'] = $info['prefix']?$info['prefix'].' ['.$info['prefixYear'].'] '.sprintf("%02d",$info['list']).'号':'';
        $content =neirong($info['content']);
        $date = isset($info['issueDate'])&&$info['issueDate']?$info['issueDate']:date('Y年m月d日',strtotime($info['time']));
        $tag = implode(' ',explode(',',$info['tag']));
        $html = <<<efo
    <div class="nop-fill-box document-content">
        <div class="document-title">{$info['issueUnit']}</div>
        <div class="document-sub-title">{$info['preText']}</div>
        <div class="divider"></div>
        <div class="document-content-title">{$info['title']}</div>
        <div class="department-title">{$info['department']}：</div>
        <div class="document-text" data-op-type="text">
          {$content}
        </div>
        <div class="file-content">
        {$file}
        </div>
        <div class="signed" data-op-type="block">
            <div>{$info['issueUnit']}</div>
            <div>$date</div>
           <input id="dw"  type="hidden" value='{$info['issueUnit']}'/>
           <input id="edw"  type="hidden" value=''/>
           <input id="mdtext"  type="hidden" value='公章'/>
            <div id="sealdiv" style="position: absolute;right: 0;top: -50px">
                <canvas id="canvas" width="250" height="250"></canvas>
            </div>
        </div>
         <div class="template-footer">
            <div>主题词：{$tag}</div>
            <div>抄送：{$info['copyDept']}</div>
            <div>印发：{$info['issuedDept']}</div>
        </div>
    </div>
efo;

        $html = <<<eof
                    <div id="content-box" style="display: none">
                      

                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                     <div data-op-type='mix-box' class="template-body">
                       
                        $html
                        </div>
                    </div>

eof;
        $print = new printClass();
        $html=$html. $this->style().$this->js();
        return $print->showPrint($html,'portrait',['padding'=>"10mm 10mm 20mm 10mm",'simplePageNum'=>false]);
    }


    public function js(): string
    {
        return <<<eof
<script>
$(function (){
    //绘制印章
    createSealEx2();
})

    function createSealEx2(){
       var dw = document.getElementById("dw");
       var edw = document.getElementById("edw");
       var mdtext = document.getElementById("mdtext");  
       var tuzhangdiv = document.getElementById("sealdiv"); 
       tuzhangdiv.innerHTML ="<canvas id='canvas' width='160' height='160'></canvas>";
       createSeal11('canvas',dw.value,mdtext.value);
        
    }
     
    function createSeal11(id,company,name){
     
    var canvas = document.getElementById(id);  
    var context = canvas.getContext('2d');
     
    // 绘制印章边框   
    var width=canvas.width/2;
    var height=canvas.height/2;
    context.lineWidth=3;
    context.strokeStyle="#f00";
    context.beginPath();
    context.arc(width,height,78,0,Math.PI*2);
    context.stroke();
    context.save(); 
     
    // context.lineWidth=1;
    // context.strokeStyle="#f00";
    // context.beginPath();
    // context.arc(width,height,75,0,Math.PI*2);
    // context.stroke();
    // context.save(); 
 
    //画五角星
    create5star(context,width,height,25,"#f00",0);
 
    // 绘制印章名称   
    context.font = '18px 宋体';
    context.textBaseline = 'middle';//设置文本的垂直对齐方式
    context.textAlign = 'center'; //设置文本的水平对对齐方式
    context.lineWidth=1;
    context.fillStyle = '#f00';
    context.fillText(name,width,height+53);
 
    // 绘制印章单位   
    context.translate(width,height);// 平移到此位置,
    context.font = '20px 宋体'
    var count = company.length;// 字数   
    var angle = 4*Math.PI/(3*(count - 1));// 字间角度   
    var chars = company.split("");   
    var c;
    for (var i = 0; i < count; i++){
        c = chars[i];// 需要绘制的字符   
        if(i==0)
            context.rotate(5*Math.PI/6);
        else
          context.rotate(angle);
        context.save(); 
        context.translate(64, 0);// 平移到此位置,此时字和x轴垂直   
        context.rotate(Math.PI/2);// 旋转90度,让字平行于x轴   
        context.fillText(c,0, 5);// 此点为字的中心点   
        context.restore();             
    }
 
     
}
 
     
   function createSeal(id,company,ecompany,name){
        var canvas = document.getElementById(id); 
        var context = canvas.getContext('2d');    
        context.translate(0,0);//移动坐标原点 
        // 绘制印章边框   
        var width=canvas.width/2;
        var height=canvas.height/2;
        //边框1
        context.lineWidth=2;
        context.strokeStyle="#f00";
        context.beginPath();
        context.arc(width,height,78,0,Math.PI*2);
        context.stroke();
        context.save(); 
         
        //边框2
        context.lineWidth=1;
        context.strokeStyle="#f00";
        context.beginPath();
        context.arc(width,height,63,0,Math.PI*2);
        context.stroke();
        context.save();
     
     
        //画五角星
        create5star(context,width,height,20,"#f00",0);
         
        // 绘制印章类型
        context.font = 'bolder 15px SimSun';
        context.textBaseline = 'middle';//设置文本的垂直对齐方式
        context.textAlign = 'center'; //设置文本的水平对对齐方式
        context.lineWidth=1;
        context.fillStyle = '#f00';
        context.fillText(name,width,height+50);
         
         
        // 绘制印章中文单位   
        context.translate(width,height);// 平移到此位置, 
        context.font = 'bolder 18px SimSun'
        var count = company.length;// 字数   
        var angle = 4*Math.PI/(3*(count-1));// 字间角度   
        var chars = company.split("");   
        var c;
        for (var i = 0; i < count; i++){
            c = chars[i];// 需要绘制的字符   
            if(i==0)
                context.rotate(5*Math.PI/6);
            else
              context.rotate(angle);
            context.save(); 
            // 平移到此位置,此时字和x轴垂直，第一个参数是与圆外边的距离，越大距离越近   
            context.translate(52, 0);
            context.rotate(Math.PI/2);// 旋转90度,让字平行于x轴   
            context.fillText(c,0, 5);// 此点为字的中心点   
            context.restore();             
        }
        //绘制印章英文单位
        context.translate(width-80,height-80);// 平移到此位置,
        context.font = 'bolder 10px SimSun';
        var ecount = ecompany.length;// 字数   
        var eangle = (5*Math.PI)/(3*(ecount));// 字间角度   
        var echars = ecompany.split("");   
        var ec;
        for (var j = 0; j < ecount; j++){
            ec = echars[j];// 需要绘制的字符   
            if(j==0)
                context.rotate(6*Math.PI/7-1);
            else
              context.rotate(eangle);
            context.save(); 
            // 平移到此位置,此时字和x轴垂直，第一个参数是与圆外边的距离，越大距离越近   
            context.translate(74, 0);
            context.rotate(Math.PI/2);// 旋转90度,让字平行于x轴   
            context.fillText(ec,0, 4.8);// 此点为字的中心点   
            context.restore();             
        }
     
  
} 
 
 //绘制五角星  
   function create5star(context,sx,sy,radius,color,rotato){
        context.save();  
        context.fillStyle=color;  
        context.translate(sx,sy);//移动坐标原点  
        context.rotate(Math.PI+rotato);//旋转  
        context.beginPath();//创建路径  
        var x = Math.sin(0);  
        var y= Math.cos(0);  
        var dig = Math.PI/5 *4;  
        for(var i = 0;i< 5;i++){//画五角星的五条边  
         x = Math.sin(i*dig);  
         y = Math.cos(i*dig);  
         context.lineTo(x*radius,y*radius);  
        }   
        context.closePath();  
        context.stroke();  
        context.fill();  
        context.restore();  
    }
</script>
eof;

    }

    /**
     * 打印样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
        <style>
         body{background-color: #AAAAAA;}
         .template-body{}
         .file-content{line-height: 30px}
         .file-content a{font-family: "仿宋", sans-serif;font-weight: 400;font-size: 16px}
        .template-body div{font-family: "宋体", sans-serif;font-style: normal;}
        .document-title{color:rgb(222, 83, 112);width: 100%;text-align: center;font-size: 36px;font-weight: 700}
        .document-sub-title{font-weight: 400;font-size: 18px;color: rgb(222, 83, 112);text-align: center;margin-top: 40px}
        .divider{width: 95%;margin: 10px auto;height: 5px;background-color: #DE5370}
        .document-content{width: 90%;margin: 20px auto;}
        .document-content-title{text-align: center;font-weight: 700;font-size: 28px;padding: 20px}
        .department-title{font-weight: 400;font-size: 16px;}
        .document-text{margin-top: 20px;font-family: "宋体", sans-serif;line-height: 14px;font-weight: 400;font-size: 16px;}
        .document-text p{font-family: "宋体", sans-serif;line-height: 36px;font-weight: 400;font-size: 16px;}
        .signed{position: relative;text-align: right;line-height: 30px;margin-top: 20px;padding: 10px;font-size: 16px;}
        .template-footer{line-height: 36px;font-weight: 400;font-size: 16px;margin-top: 40px}
        .template-footer>div:first-child{font-weight: bold}
        </style>
eof;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '停用') {
                    $warn = "不是停用状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
